//
//  GroupBuyMainViewController.m
//  cityStar
//
//  Created by apple on 14/12/13.
//  Copyright (c) 2014年 tiny. All rights reserved.
//

#import "GroupBuyMainViewController.h"
#import "HTDefine.h"
#import "SideViewController.h"
#import "GroupBuyTableViewCell.h"
#import "Define.h"
#import "SingleTableView.h"

#import "HWSearchViewController.h"
#import "GroupBuyMessage.h"
#import "SVPullToRefresh.h"
#import "WaresDetailViewController.h"

NSString *const groupBuyTableViewCellID = @"groupBuyTableViewCellID";

@interface GroupBuyMainViewController ()<UITableViewDelegate,UITableViewDataSource,SingleTableViewDelegate>

@property (nonatomic,weak) IBOutlet UITableView *tableView;
@property (nonatomic,weak) GroupBuyTableViewCell *groupBuyTableViewCell;
@property (nonatomic,weak) IBOutlet UIButton *btnAllTypes;
@property (nonatomic,weak) IBOutlet UIButton *btnNoopsyche;
@property (nonatomic,strong) NSMutableArray *requestArray;

@property (nonatomic, weak) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIImageView *typeImageView;
@property (strong, nonatomic) SingleTableView *typeSingleTableView;

@property (nonatomic, weak) IBOutlet UIImageView *noopsycheImageView;
@property (strong, nonatomic) SingleTableView *noopsycheSingleTableView;
@property (nonatomic, assign) int page;
@property (nonatomic, assign) int order;
@property (nonatomic, strong) NSString * typename;
@property (nonatomic, assign) int type;


@end

@implementation GroupBuyMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNavBar];
    // Do any additional setup after loading the view.
    [self setUpTableViews];
//    [self webRequest_GetGroupBuyMessgaeisMore:NO];
    self.typename = @"";
    __weak typeof(self)weakSelf = self;
    [self.tableView addPullToRefreshWithActionHandler:^{
        self.page = 0;
        self.order = 0;
        self.type = -1;
        [weakSelf webRequest_GetGroupBuyMessgaeisMore:NO andOrder:weakSelf.order];
    }];
    [self.tableView addInfiniteScrollingWithActionHandler:^{
        [weakSelf webRequest_GetGroupBuyMessgaeisMore:YES andOrder:weakSelf.order];
    }];
    [self.tableView triggerPullToRefresh];
}

- (void)initNavBar{
    self.navigationItem.title = @"团购";
    
    UISwipeGestureRecognizer* recognizer;
    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    recognizer.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:recognizer];
    
    UIButton * regBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    regBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [regBtn setTitleColor:rgba(133, 133, 133, 1) forState:UIControlStateHighlighted];
    [regBtn setImage:[UIImage imageNamed:@"bsearch"] forState:UIControlStateNormal];
    [regBtn setImage:[UIImage imageNamed:@"bsearch_touch"] forState:UIControlStateHighlighted];
    [regBtn addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * iHaveNewsBtnItem = [[UIBarButtonItem alloc]initWithCustomView:regBtn];
    self.navigationItem.rightBarButtonItem = iHaveNewsBtnItem;
    
    UIButton *btnSide = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    [btnSide setImage:[UIImage imageNamed:@"more"] forState:UIControlStateNormal];
    [btnSide setImage:[UIImage imageNamed:@"more_touch"] forState:UIControlStateHighlighted];
    [btnSide addTarget:self action:@selector(sideMove) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *bbtmLeft = [[UIBarButtonItem alloc]initWithCustomView:btnSide];
    self.navigationItem.leftBarButtonItem = bbtmLeft;
}

-(void)viewWillAppear:(BOOL)animated
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >=7.0) {
        self.navigationController.navigationBar.translucent = NO; //禁止半透明毛玻璃效果
        self.navigationController.navigationBar.tintColor = kWhiteNavTitleColor; //返回按钮颜色
        self.navigationController.navigationBar.barTintColor = [UIColor whiteColor]; //bar背景颜色
        self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:kWhiteNavTitleColor,NSFontAttributeName:[UIFont boldSystemFontOfSize:18]}; //标题颜色
        self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    }else{
        [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]]; //bar背景颜色
        self.navigationController.navigationBar.translucent = NO;
        self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:kWhiteNavTitleColor,NSFontAttributeName:[UIFont boldSystemFontOfSize:18]};
        self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    }
}

-(void)webRequest_GetGroupBuyMessgaeisMore:(BOOL)isMore andOrder:(int)order
{
    NSString *url = @"";
    NSString *postUrl = [NSString stringWithFormat:@"%@/type/%i/page/%i/order/%i/city/%@",KinterFace_goodsGroup,self.type,self.page,order,[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]?[KStandUserDefaults objectForKey:KUserDefaultKey_PersonalCityID]:@"122"];
    url =  postUrl;
    
    if([self.typename isEqualToString:@""])
    {
        
    }
    if(self.order)
    {
        
    }
    
    [HttpRequestManager getMethod:url parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            if (isMore) {
                [self.requestArray addObjectsFromArray:response[@"value"][@"content"]];
//                self.page = self.page + 1;
            }else{
                self.requestArray = [[NSMutableArray alloc]initWithArray:response[@"value"][@"content"]];
//                self.page = 0;
            }
//            self.requestArray = [[NSArray alloc]initWithArray:response[@"value"][@"content"]];
            self.page = self.page + 1;

            [self.tableView reloadData];
        }else{
            [SVProgressHUD showErrorWithStatus:errMsg];
        }
    }];
    if (isMore) {
        [self.tableView.infiniteScrollingView stopAnimating];
    }else{
        [self.tableView.pullToRefreshView stopAnimating];
    }
    

//    [self.tableView reloadData];
}

//}

#pragma mark - UITableViewDelegate and UITableViewDataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.groupBuyTableViewCell = [tableView dequeueReusableCellWithIdentifier:groupBuyTableViewCellID];
    self.groupBuyTableViewCell.selectionStyle = UITableViewCellSelectionStyleGray;
//    [self.groupBuyTableViewCell configWithMessage:message];
    GroupBuyMessage *groupBuy = [GroupBuyMessage objectFromDictionary:self.requestArray[indexPath.row]];
    [self.groupBuyTableViewCell configWithMessgae:groupBuy];
    
    return self.groupBuyTableViewCell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [GroupBuyTableViewCell heightOfTableCell];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.requestArray.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GroupBuyMessage *groupBuy = [GroupBuyMessage objectFromDictionary:self.requestArray[indexPath.row]];
    WaresDetailViewController *waresDetailViewController = [[WaresDetailViewController alloc]initWithCommodityID:groupBuy.object_id];
    [self.navigationController pushViewController:waresDetailViewController animated:YES];
    [tableView reloadData];
}


-(void)setUpTableViews
{
    
    [self.tableView registerNib:[GroupBuyTableViewCell nib] forCellReuseIdentifier:groupBuyTableViewCellID];
}

#pragma mark - Actions
-(IBAction)allTypes_Touch:(id)sender
{
    if(self.btnAllTypes.selected == NO)
    {
        self.btnAllTypes.selected = YES;
    }else{
        self.btnAllTypes.selected = NO;
    }
    self.btnNoopsyche.selected = NO;

    [self.typeSingleTableView showFromPosition:CGPointMake(0, 25) inViewController:self dataType:SingleTableViewDataTypeSortModel];
    self.typeSingleTableView.dataArray = @[@"全部分类",@"新增团购",@"美食",@"休闲娱乐",@"电影",@"酒店",@"KTV",@"旅游",@"丽人",@"生活服务",@"外卖"];
}

-(IBAction)noopsyche_Touch:(id)sender
{
    if(self.btnNoopsyche.selected == NO)
    {
        self.btnNoopsyche.selected = YES;
    }else{
        self.btnNoopsyche.selected = NO;
    }
    self.btnAllTypes.selected = NO;
    [self.noopsycheSingleTableView showFromPosition:CGPointMake(0, 25) inViewController:self dataType:SingleTableViewDataTypeSortModel];
    self.noopsycheSingleTableView.dataArray =@[@"智能排序",@"价格从低到高",@"价格从高到低",@"评论排序"];
}

- (void)searchAction{
    HWSearchViewController *hwSearchVC = [[HWSearchViewController alloc]init];
    hwSearchVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:hwSearchVC animated:YES];
}

- (void)handleSwipeFrom:(UISwipeGestureRecognizer*)recognizer {
    [self sideMove];
    //    [self.view removeGestureRecognizer:recognizer];
}

- (void)sideMove{
    [[SideViewController shareVc] showLeftView];
}

#pragma mark - singleTableViewDelegate
- (SingleTableView *)typeSingleTableView
{
    if (!_typeSingleTableView) {
        _typeSingleTableView = [[SingleTableView alloc] init];
        _typeSingleTableView.delegate = self;
        [self addChildViewController:_typeSingleTableView];
        [self.view addSubview:_typeSingleTableView.view];
        [self.view bringSubviewToFront:self.topView];
        _typeSingleTableView.arrawImageView = self.typeImageView;
    }
    return _typeSingleTableView;
}

- (void)singleTableView:(SingleTableView *)tableView didSelectedCellAtIndexPath:(NSIndexPath *)indexPath
{
    self.btnAllTypes.selected = NO;
    self.btnNoopsyche.selected = NO;
    if (tableView == self.typeSingleTableView) {
        NSString *celltest = @[@"全部分类",@"新增团购",@"美食",@"外卖",@"电影",@"酒店",@"KTV",@"旅游",@"丽人",@"生活服务",@"休闲娱乐"][indexPath.row];
        self.typename = celltest;
        if([self.typename  isEqualToString: @"全部分类"])
        {
            self.typename = @"";
        }
        if (celltest.length > 4) {
            NSString *btnTitle = [NSString stringWithFormat:@"%@..",[celltest substringWithRange:NSMakeRange(0, 4)]];
            [self.btnAllTypes setTitle:btnTitle forState:UIControlStateNormal];
        }else{
            [self.btnAllTypes setTitle:celltest forState:UIControlStateNormal];
        }
        self.page = 0;
        self.type = (int)indexPath.row-1;
        [self webRequest_GetGroupBuyMessgaeisMore:NO andOrder:self.order];
    }else
    {
        NSString *celltest =@[@"智能排序",@"价格从低到高",@"价格从高到低",@"评论排序"][indexPath.row];
        if (celltest.length > 4) {
            NSString *btnTitle = [NSString stringWithFormat:@"%@..",[celltest substringWithRange:NSMakeRange(0, 4)]];
            [self.btnNoopsyche setTitle:btnTitle forState:UIControlStateNormal];
        }else{
            [self.btnNoopsyche setTitle:celltest forState:UIControlStateNormal];
        }
        self.order = (int)indexPath.row;
        self.page = 0;
        [self webRequest_GetGroupBuyMessgaeisMore:NO andOrder:self.order];
    }
}

- (SingleTableView *)noopsycheSingleTableView
{
    if (!_noopsycheSingleTableView) {
        _noopsycheSingleTableView = [[SingleTableView alloc] init];
        _noopsycheSingleTableView.delegate = self;
        [self addChildViewController:_noopsycheSingleTableView];
        [self.view addSubview:_noopsycheSingleTableView.view];
        [self.view bringSubviewToFront:self.topView];
        _noopsycheSingleTableView.arrawImageView = self.noopsycheImageView;
    }
    return _noopsycheSingleTableView;
}

-(void)cancleTabelView
{
    self.btnAllTypes.selected = NO;
    self.btnNoopsyche.selected = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
